import store from '@/store'
import {
	Base64
} from './base64'
import {
	createNode,
	hasClass,
	addClass,
	removeClass,
	arrayRemove
} from '@/utils'
import {
	mobile_faceContent
} from './face_mobile'
import Gift from './Gift'
import { openPhotoSwipe } from '@/utils/pswp'
let ImageBase = process.env.BASE_URL
export default class ChatDisplay {
	constructor(container, xMessager, chatMode = 0, infosum = 0, autoscroll = true) {
		this.container = container
		this.infosum = infosum
		this.autoscroll = autoscroll
		this.xMessager = xMessager
		this.chatMode = chatMode
		this.giftArr = []
		this.giftTopArr = ['9rem','13rem','17rem']
		this.giftShowNum = 3
		this.giftDestroyedTime = 2500
		this.scrollContainer = this.container.parentNode
		if(this.scrollContainer) {
			this.barrageTip = this.scrollContainer.parentNode.querySelector('.barrage-tip')
		}
		this.init()
	}
	init() {
		this.scrollContainer.addEventListener('scroll', () => {
			if(this.scrollContainer.scrollTop !== 0) {
				if(this.scrollContainer.scrollTop === this.scrollContainer.scrollHeight - this.scrollContainer.clientHeight) {
					console.log('滚动到底了')
					this.autoscroll = true
					if(this.barrageTip && this.barrageTip.classList.contains('show')) {
						this.barrageTip.classList.remove('show')
					}
				} else {
					console.log('滚动没到底了')
					this.autoscroll = false
				}
			}
		}, false)
		if(this.barrageTip) {
			this.barrageTip.addEventListener('click', () => {
				this.autoscroll = true
				this.rolling()
			}, false)
		}
	}
	time() {
		var date = new Date();
		var now = (date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()) + ':' +
			(date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes());
		return now;
	}
	disinout(info, roompara) {
		if (this.xMessager.level < roompara.user_info_level || info.levelinroom < 20) {
			return false
		}
		if (info.levelinroom !== 6000) {
			if (roompara.display_yk_inout == 1 || (roompara.display_inout == 1 && roompara.display_yk_inout == 0 && info.levelinroom >=
					100)) {
				var type = (info.type == 1) ? '进入直播间' : '离开直播间';
				var prefix = (info.type == 1) ? '欢迎 ' : '欢送 '; //;
				if ((info.nicegid + "").length > 8 && info.type == 1) {
					if (this.chatMode === 1) {
						var t = '<li><div class="message"><span class="content">' + prefix + '<span class="nikename">' + info.from_nickname +
							'</span>' + '  ' + type + '</span></div>';
						t += '</li>';
						this.new_insert(t, 0);
					} else {
						this.insert("<span class='chat-red'>" + prefix + "</span> " + info.from_nickname + ' ' +
							"<span class='chat-red'>" + type + "</span>")
					}
					return;
				}
				//只显示进入房间信息
				if (this.chatMode === 1) {
					var t = '<li><div class="message"><span class="userrand ">提示：</span><span class="nikename">' + info.from_nickname +
						'</span><span class="content" style="color:red;margin-left:0.266667rem;">' + type + '</span></div>';
					t += '</li>';
					this.new_insert(t, 0);
				} else {
					var t = '<li><em></em><span class="chat_user">' + info.from_nickname + '</span><span class="chat_area">' + type +
						'</span>';
					this.insert(t, 0);
				}
			}
		}
	}
	insert(info, is_sys, is_my_message, level) {
		if (info == "") return;
		var li;
		if (is_sys) {
			li = createNode(`<li><em></em><span class="chat_user">系统消息:</span><span class="chat_area">${info}</span></li>`)
		} else {
			li = createNode(info);
			if (li.nodeName !== "LI") {
				li = createNode("<li>" + info + "</li>")
			}
		}
		this.container.appendChild(li);
		this.infosum++;
		if (this.infosum > 50) this.displaylastmsg();
		this.rolling();
	}
	new_insert(info, is_sys, is_my_message, level) {
		if (info == "") return;
		var li;
		if (is_sys) {
			li = createNode(
				`<li><div class="message system_message"><span class="chat_user">系统消息:</span><span class="chat_area">${info}</span></div></li>`
			)
		} else {
			li = createNode(info);
			if (li.nodeName !== "LI") {
				li = createNode("<li><div class='message'>" + info + "</div></li>")
			}
		}
		this.container.appendChild(li)
		this.infosum++;
		if (this.infosum > 50) this.displaylastmsg()
		this.rolling();
	}
	rolling() {
		if(!this.autoscroll) {
			if(this.barrageTip && !this.barrageTip.classList.contains('show')) {
				this.barrageTip.classList.add('show')
			}
			return false
		}
		if (this.autoscroll == 1) {
			this.container.parentNode.scrollTop = this.container.parentNode.scrollHeight + 1000
			let nodeArr = Array.from(this.container.children)
			if(nodeArr[nodeArr.length - 1].querySelector('.chat_load_img')){
				nodeArr[nodeArr.length - 1].querySelector('.chat_load_img').onload = () => this.container.parentNode.scrollTop = this.container.parentNode.scrollHeight + 1000
				nodeArr[nodeArr.length - 1].querySelector('.chat_load_img').addEventListener('click',function(e){
					let arr = [],src = e.target.src
					arr.push({
							src: src.replace(/(-\d+x\d+)?_size/, ""),
							w: 180,
							h: 180
					}),
					openPhotoSwipe(arr, 0)
				})
			}
		}
	}
	displaylastmsg() {
		let length = this.container.childNodes.length - 20
		Array.from(this.container.childNodes).forEach((item, index) => {
			if (index < length) {
				this.container.removeChild(item)
			}
		})
		this.infosum = 20;
	}
	template0_display_chatmessage(chatdata, is_my_message) {
		if (document.querySelector(`[data_msg_id="${chatdata.msg_id}"]`)) {
			return false
		}
		if (chatdata.type != 9) {
			chatdata.message = mobile_faceContent(chatdata.message);
			chatdata.message = chatdata.message.replace(/</g, '&#60;').replace(/>/g, '&#62;').replace(/\/b/g, '&#47;b');
			chatdata.message = chatdata.message.replace(/&#47;b(\d+)/g, (match,$1)=>{
				return `<img width='20' height='20' src='${require(`../../assets/images/face/${$1}.png`)}'>`
			});
			chatdata.message = chatdata.message.replace(
				/\[((https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])\]/g,
				"<img class='chat_load_img' src='$1' style='max-width:100%;height:auto'>");
		}
		// var t = '<li data_msg_id="'+ chatdata.msg_id +'"><em></em><span class="chat_user">' + chatdata.from_nickname + '：</span><span class="chat_area">' + chatdata.message + '</span></li>';
		if (chatdata.from_level == 500) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="teacher"></i></span><span class="chat_user">' + chatdata.from_nickname +
				'：</span><span class="chat_area">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 900) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="admin"></i></span><span class="chat_user">' + chatdata.from_nickname +
				'：</span><span class="chat_area">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 2000) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="shi"></i></span><span class="chat_user">' + chatdata.from_nickname +
				'：</span><span class="chat_area">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 4000) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="tuan"></i></span><span class="chat_user">' + chatdata.from_nickname +
				'：</span><span class="chat_area">' + chatdata.message + '</span></div>';
		} else {
			var t = '<li data_msg_id=' + chatdata.msg_id + '><div class="message"><span class="userrand "><i class="rank' +
				chatdata.title + '"></i></span><span class="chat_user">' + chatdata.from_nickname +
				'：</span><span class="chat_area">' + chatdata.message + '</span></div>';
		}
		t += '</li>';
		this.insert(t, 0, is_my_message, chatdata.liveinroom);
	}
	template1_display_chatmessage(chatdata, is_my_message) {
		if (document.querySelector(`[data_msg_id="${chatdata.msg_id}"]`)) {
			return false
		}
		if (chatdata.type != 9) {
			chatdata.message = mobile_faceContent(chatdata.message);
			chatdata.message = chatdata.message.replace(/</g, '&#60;').replace(/>/g, '&#62;').replace(/\/b/g, '&#47;b');
			chatdata.message = chatdata.message.replace(/&#47;b(\d+)/g, (match,$1)=>{
				return `<img width='20' height='20' src='${require(`../../assets/images/face/${$1}.png`)}'>`
			});
			chatdata.message = chatdata.message.replace(
				/\[((https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])\]/g,
				"<img class='chat_load_img' src='$1' style='max-width:100%;height:auto'>");
		}
		if (chatdata.from_level == 500) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="teacher"></i></span><span class="nikename">' + chatdata.from_nickname +
				'：</span><span class="content">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 900) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="admin"></i></span><span class="nikename">' + chatdata.from_nickname +
				'：</span><span class="content">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 2000) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="shi"></i></span><span class="nikename">' + chatdata.from_nickname +
				'：</span><span class="content">' + chatdata.message + '</span></div>';
		} else if (chatdata.from_level == 4000) {
			var t = '<li data_msg_id=' + chatdata.msg_id +
				'><div class="message"><span class="userrand "><i class="tuan"></i></span><span class="nikename">' + chatdata.from_nickname +
				'：</span><span class="content">' + chatdata.message + '</span></div>';
		} else {
			var t = '<li data_msg_id=' + chatdata.msg_id + '><div class="message"><span class="userrand "><i class="rank' +
				chatdata.title + '"></i></span><span class="nikename">' + chatdata.from_nickname +
				'：</span><span class="content">' + chatdata.message + '</span></div>';
		}
		t += '</li>';
		this.new_insert(t, 0, is_my_message, chatdata.liveinroom);
	}
	pic_chat_insert(info, is_sys, is_my_message, is_secret) {
		var li, li2;
		if (is_sys) {
			li = createNode(
				'<li class="public_chat"><div class="chat_user_des"><span class="chat_user_name" style="color:red;">系统消息</span></div><div class="chat_content"><span class="chat_text">' +
				info + '</span></div></li>');
			this.container.appendChild(li);
		} else {
			li = createNode(info);
			if (li.nodeName !== "LI") {
				li = createNode(
					'<li><div class="chat_user_des"><span class="chat_user_name">提示：</span></div><div class="chat_content">' + info +
					'</div><li>');
			}
			this.container.appendChild(li);
		}
		this.infosum++;
		if (this.infosum > 50) this.displaylastmsg();
		this.rolling();
	}
	private_chat_display_chatmessage(chatdata, is_my_message) {
		if (chatdata.type != 9) {
			chatdata.message = mobile_faceContent(chatdata.message);
			chatdata.message = chatdata.message.replace(/</g, '&#60;').replace(/>/g, '&#62;').replace(/\//g, '&#47;b');
			chatdata.message = chatdata.message.replace(/&#47;b(\d+)/g, "<img width='20' height='20' src='" + ImageBase +
				"static/images/face/$1.png'>");
		}
		var t = '';
		t += '<li data_msg_id="' + chatdata.msg_id + '"><span class="time">' + this.time() + '</span>';
		t += '<span class="nickname">' + chatdata.from_nickname + '</span>';
		if (chatdata.touid != 0) {
			t += '对<span class="me">' + chatdata.to_nickname + '</span>说:';
		}
		t += '<span class="chat_content">' + chatdata.message + '</span></li>';
		this.pic_chat_insert(t, 0);
	}
	diaplayflower(user) {
		var t = '<li><em></em><span class="chat_user">' + user.fromwho.nickname +
			'</span><span class="chat_area">给老师送了一个 <img src="' + ImageBase +
			'static/images/zan.png" class="room-zan-icon"/></span>';
		this.insert(t, 0);
	}
	new_disflower(user) {
		if (user.fromwho) {
			if (user.fromwho.levelinroom == 500) {
				var t = '<li><div class="message"><span class="userrand "><i class="teacher"></i></span><span class="nikename">' +
					user.fromwho.nickname + '</span><span class="content zan_content">给老师送了一个 <img src="' + ImageBase +
					'/resources/images/roomwap/zan.png" class="room-zan-icon"/></span></div>';
			} else if (user.fromwho.levelinroom == 900) {
				var t = '<li><div class="message"><span class="userrand "><i class="admin"></i></span><span class="nikename">' +
					user.fromwho.nickname + '</span><span class="content zan_content">给老师送了一个 <img src="' + ImageBase +
					'/resources/images/roomwap/zan.png" class="room-zan-icon"/></span></div>';
			} else if (user.fromwho.levelinroom == 2000) {
				var t = '<li><div class="message"><span class="userrand "><i class="shi"></i></span><span class="nikename">' +
					user.fromwho.nickname + '</span><span class="content zan_content">给老师送了一个 <img src="' + ImageBase +
					'/resources/images/roomwap/zan.png" class="room-zan-icon"/></span></div>';
			} else if (user.fromwho.levelinroom == 4000) {
				var t = '<li><div class="message"><span class="userrand "><i class="tuan"></i></span><span class="nikename">' +
					user.fromwho.nickname + '</span><span class="content zan_content">给老师送了一个 <img src="' + ImageBase +
					'/resources/images/roomwap/zan.png" class="room-zan-icon"/></span></div>';
			} else {
				var t = '<li><div class="message"><span class="userrand "><i class="rank' + user.title +
					'"></i></span><span class="nikename">' + user.fromwho.nickname +
					'</span><span class="content zan_content">给老师送了一个 <img src="' + ImageBase +
					'/resources/images/roomwap/zan.png" class="room-zan-icon"/></span></div>';
			}
		}
		t += '</li>';
		this.new_insert(t, 0);
	}
	public_chat_display_chatmessage(chatdata, is_my_message) {
		if (this.chatMode === 1) {
			this.template1_display_chatmessage(chatdata, is_my_message)
		} else if (this.chatMode === 0) {
			this.template0_display_chatmessage(chatdata, is_my_message)
		}
	}
	common_chat_display_chatmessage(chatdata, is_my_message) {
		if (!chatdata.secret) {
			this.public_chat_display_chatmessage(chatdata, is_my_message)
		}
	}
	common_insert(info, is_sys, is_my_message, level) {
		if (this.chatMode === 0) {
			this.insert(info, is_sys, is_my_message, level)
		} else if (this.chatMode === 1) {
			this.new_insert(info, is_sys, is_my_message, level)
		}
	}
	freeFlower(data) {
		if (this.chatMode === 1) {
			this.new_disflower(data)
		} else if (this.chatMode === 0) {
			this.diaplayflower(data)
		}
	}
	giftDestroyed(){
		let afterGift = this.giftArr[this.giftShowNum - 1]
		if(afterGift){
			afterGift.createGift()
			this.openGiftTimer(afterGift,this.giftShowNum - 1)
		}
		this.giftArr.forEach((item,index)=>{
			if(index <= this.giftShowNum - 1 && this.giftTopArr[index]){
				item.updateGiftTop(this.giftTopArr[index])
			}
		})
	}
	dertroyGift(gift,next){
		if(this.giftArr.length && gift){
			let index = this.giftArr.findIndex((item)=>{
				return item.giftId === gift.giftId && item.giftFromUid === gift.giftFromUid  && item.giftToUid === gift.giftToUid
			})
			arrayRemove(this.giftArr,index)
			gift.detroyGift()
			this.giftArr.forEach((item,index)=>{
				item.updateGiftTop(this.giftTopArr[index])
			})
		}
	}
	openGiftTimer(gift,next){
		gift.giftTimer = setTimeout(()=>{
			this.dertroyGift(gift,next)
		},gift.giftHideTime)
	}
	disgift(giftInfo) {
		let index = -1
		for (let [i, item] of this.giftArr.entries()) {
			if(item && item.giftId){
				if(giftInfo.id === item.giftId && item.giftFromUid === giftInfo.from_uid && item.giftToUid === giftInfo.to_uid){
					index = i
					break
				}
			}
		}
		let gift
		if(index === -1){
			gift = new Gift(giftInfo,document.querySelector('.template-room-outer-wrap'))
			this.giftArr.push(gift)
			if(this.giftArr.length > this.giftShowNum){
				this.giftArr.forEach((item,index)=>{
					if(index < this.giftArr.length - this.giftShowNum){
						if(item.giftTimer){
							clearTimeout(item.giftTimer)
							item.giftTimer = null
							this.dertroyGift(item)
						}
					}
				})
			}
			gift.createGift()
			this.openGiftTimer(gift,true)
			this.giftArr.forEach((item,index)=>{
				item.updateGiftTop(this.giftTopArr[index])
			})
		}else{
			gift = this.giftArr[index]
			if(gift.giftTimer){
				clearTimeout(gift.giftTimer)
				gift.giftTimer = null
			}
			gift.sum += giftInfo.sum
			gift.highlightGift()
			this.openGiftTimer(gift,true)
		}
	}
	deleteInfo(data_msg_id) {
		let liNode = document.querySelector(`[data_msg_id="${data_msg_id}"]`)
		if (liNode) {
			liNode.parentNode.removeChild(liNode)
		}
	}
	filterChatdataMessage(chatdata) {
		if (chatdata.type != 9) {
			chatdata.message = mobile_faceContent(chatdata.message);
			chatdata.message = chatdata.message.replace(/</g, '&#60;').replace(/>/g, '&#62;').replace(/\/b/g, '&#47;b');
			chatdata.message = chatdata.message.replace(/&#47;b(\d+)/g, (match,$1)=> `<img class='private-face-img' width='20' height='20' src='${require(`../../assets/images/face/${$1}.png`)}'>`);
			chatdata.message = chatdata.message.replace(
				/\[((https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])\]/g,
				"<img class='chat_load_img' src='$1' style='max-width:100%;height:auto'>");
		}
	}
	clearChatWrap(){
		this.container.innerHTML = ''
	}
}
